package com.ktg.mes.rec.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.domain.entity.SysDictData;
import com.ktg.common.core.domain.model.LoginUser;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.dv.domain.DvMachinery;
import com.ktg.mes.dv.service.IDvMachineryService;
import com.ktg.mes.md.domain.MesScalesOrderItem;
import com.ktg.mes.md.service.IMesScalesOrderItemService;
import com.ktg.mes.pro.domain.OrderStatus;
import com.ktg.mes.pro.domain.ProTask;
import com.ktg.mes.pro.domain.ProTaskDeviceProcess;
import com.ktg.mes.pro.domain.ProWorkorder;
import com.ktg.mes.pro.service.IProTaskDeviceProcessService;
import com.ktg.mes.pro.service.IProTaskService;
import com.ktg.mes.pro.service.IProWaringService;
import com.ktg.mes.pro.service.IProWorkorderService;
import com.ktg.mes.rec.controller.vo.RecLRPdaAddVo;
import com.ktg.system.service.ISysDictDataService;
import com.ktg.system.service.ISysDictTypeService;
import com.ktg.system.utils.SecurityUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.rec.domain.RecLnspectionRecord;
import com.ktg.mes.rec.service.IRecLnspectionRecordService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 工序检测记录Controller
 *
 * @author byteco
 * @date 2022-11-04
 */
@RestController
@RequestMapping("/rec/recLnspectionRecord")
public class RecLnspectionRecordController extends BaseController
{
    @Autowired
    private IRecLnspectionRecordService recLnspectionRecordService;

    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IProWaringService proWaringService;

    @Autowired
    private IDvMachineryService dvMachineryService;

    @Autowired
    private IProTaskDeviceProcessService proTaskDeviceProcessService;

    @Autowired
    private IProWorkorderService proWorkorderService;

    @Autowired
    private IMesScalesOrderItemService mesScalesOrderItemService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;


    /**
     * 查询工序检测记录列表
     */
    // @PreAuthorize("@ss.hasPermi('rec:recLnspectionRecord:list')")
    @GetMapping("/list")
    public Result<IPage<RecLnspectionRecord>> list(RecLnspectionRecord recLnspectionRecord,
                                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                   HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询工序检测记录列表",req,null);
        try {
            Page<RecLnspectionRecord> page = new Page<RecLnspectionRecord>(pageNo, pageSize);
            IPage<RecLnspectionRecord> pageList = recLnspectionRecordService.queryPageList(recLnspectionRecord,page);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出工序检测记录列表
     */
    // @PreAuthorize("@ss.hasPermi('rec:recLnspectionRecord:export')")
    @Log(title = "工序检测记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RecLnspectionRecord recLnspectionRecord,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出工序检测记录列表",req,recLnspectionRecord);
        try {
            List<RecLnspectionRecord> list = recLnspectionRecordService.queryList(recLnspectionRecord);
            ExcelUtil<RecLnspectionRecord> util = new ExcelUtil<RecLnspectionRecord>(RecLnspectionRecord.class);
            util.exportExcel(response, list, "工序检测记录数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取工序检测记录详细信息
     */
    // @PreAuthorize("@ss.hasPermi('rec:recLnspectionRecord:query')")
    @GetMapping(value = "/{id}")
    public Result<RecLnspectionRecord> getInfo(@PathVariable("id") Long id,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取工序检测记录详细信息",req,null);
        try {
            return apiLog.ok(recLnspectionRecordService.getInfo(id));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增工序检测记录
     */
    // @PreAuthorize("@ss.hasPermi('rec:recLnspectionRecord:add')")
    @Log(title = "工序检测记录", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public Result<String> add(@RequestBody RecLnspectionRecord recLnspectionRecord,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增工序检测记录",req,recLnspectionRecord);
        try {
            recLnspectionRecordService.insert(recLnspectionRecord);
            if (recLnspectionRecord.isFinished()){
                ProTask task =  proTaskService.selectProTaskByTaskId(recLnspectionRecord.getTaskId());
                task.setStatus("FINISHED");
                proTaskService.updateProTask(task);
                proWaringService.isWarning(recLnspectionRecord,null);
            }


            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * PDA 采集数据
     */
    @Log(title = " PDA 采集数据", businessType = BusinessType.INSERT)
    @PostMapping(value = "padAdd")
    public Result<String> padAdd(@RequestBody RecLRPdaAddVo pdaAddVo, //字典字符串
                                 HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增工序检测记录",req,null);
        try {
            Object obj = proTaskDeviceProcessService.initOrFind(pdaAddVo.getBatchNo(),Long.valueOf(pdaAddVo.getProcessId()),pdaAddVo.getDeviceCode(),pdaAddVo.getType());
            ProTaskDeviceProcess taskDeviceProcess = null;
            if (obj instanceof ProTaskDeviceProcess){
                taskDeviceProcess = (ProTaskDeviceProcess) obj;
                String error = proTaskService.updateFromProTaskDeviceProcess(taskDeviceProcess);
                if (error != null){
                    return apiLog.fail(error);
                }
            }else {
                return apiLog.fail((String) obj);
            }


            RecLnspectionRecord recLnspectionRecord = new RecLnspectionRecord();
            recLnspectionRecord.setTaskDeviceProcessRecordId(taskDeviceProcess.getRecordId());
            recLnspectionRecord = recLnspectionRecordService.getOne(new QueryWrapper<RecLnspectionRecord>(recLnspectionRecord));
            if (recLnspectionRecord == null){
                recLnspectionRecord = new RecLnspectionRecord();
                recLnspectionRecord.setTaskId(Long.valueOf(taskDeviceProcess.getTaskId()));
                recLnspectionRecord.setBatchNo(taskDeviceProcess.getBatchNo());
                recLnspectionRecord.setTaskName(taskDeviceProcess.getTaskName());
                recLnspectionRecord.setTaskDeviceProcessRecordId(taskDeviceProcess.getRecordId());
                recLnspectionRecord.setWorkType(pdaAddVo.getType());

                DvMachinery dvMachinery = dvMachineryService.getById(taskDeviceProcess.getDeviceId());
                if (dvMachinery != null){
                    recLnspectionRecord.setMachineryId(dvMachinery.getMachineryId());
                    recLnspectionRecord.setMachineryCode(dvMachinery.getEquipmentCode());
                    recLnspectionRecord.setMachineryName(dvMachinery.getMachineryName());
                }else {
                    recLnspectionRecord.setMachineryId(0L);
                    recLnspectionRecord.setMachineryCode("");
                    recLnspectionRecord.setMachineryName("");
                }
                recLnspectionRecord.setProcessesId(taskDeviceProcess.getProcessId());
                recLnspectionRecord.setProcessesName(taskDeviceProcess.getProcessName());
            }
            if (taskDeviceProcess.getDeviceId() != null){
                DvMachinery dvMachinery = dvMachineryService.getById(taskDeviceProcess.getDeviceId());
                if (dvMachinery != null){
                    recLnspectionRecord.setMachineryId(dvMachinery.getMachineryId());
                    recLnspectionRecord.setMachineryCode(dvMachinery.getEquipmentCode());
                    recLnspectionRecord.setMachineryName(dvMachinery.getMachineryName());
                }
            }

            //跟新生产订单状态
            ProWorkorder proWorkorder = proWorkorderService.selectProWorkorderByWorkorderId(taskDeviceProcess.getWorkorderId());
            proWorkorder.setStatus(OrderStatus.product.toName());

            //跟新排产任务状态
            ProTask proTask = proTaskService.getById(taskDeviceProcess.getTaskId());
            proTask.setStatus(taskDeviceProcess.getProcessName());
            proTask.setProcessId(taskDeviceProcess.getProcessId());

            if (!StringUtils.isEmpty(pdaAddVo.getDicText())){
                JSONObject jsonObject = JSONObject.parseObject(pdaAddVo.getDicText());
                //处理桶号
                recLnspectionRecord.setToolTypeCode(jsonObject.getString("桶号"));
                jsonObject.remove("桶号");
                recLnspectionRecord.setDicText(jsonObject.toJSONString());

                //生产完成
                boolean isFinish = false;
                if (jsonObject.containsKey("生产完成")){
                    isFinish = jsonObject.getBoolean("生产完成");
                }

                if (isFinish == true){
                    //跟新生产订单状态
                    proWorkorder.setStatus(OrderStatus.productComple.toString());
                    proTask.setEndTime(new Date());
                    proTask.setIsFinish("Y");
                    //跟新销售订单完成数量
                    if (proTask.getScaleId() != null){
                        mesScalesOrderItemService.addCount(proTask.getScaleId(),0.0,0.0,proTask.getQuantity().doubleValue());
                    }
                }

                //处理检测结果
                if (jsonObject.containsKey("检测")){
                    String value = jsonObject.getString("检测");
                    SysDictData dictData = sysDictTypeService.selectDictDataByType("process_color",value);
                    if (dictData != null){
                        proTask.setColorCode(dictData.getDictValue());
                        proTaskService.updateById(proTask);
                    }
                }
            }else {
                recLnspectionRecord.setDicText("{}");
            }

            proTaskService.updateById(proTask);
            proWorkorderService.updateProWorkorder(proWorkorder);
            if (recLnspectionRecord.getId() == null){
                recLnspectionRecord.setCreateTime(new Date());
                recLnspectionRecord.setCreateBy(SecurityUtils.getUsername());
                recLnspectionRecordService.save(recLnspectionRecord);
            }else {
                recLnspectionRecord.setUpdateTime(new Date());
                recLnspectionRecord.setUpdateBy(SecurityUtils.getUsername());
                recLnspectionRecordService.updateById(recLnspectionRecord);
            }
            return apiLog.ok(recLnspectionRecord);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }



    /**
     * 修改工序检测记录
     */
    // @PreAuthorize("@ss.hasPermi('rec:recLnspectionRecord:edit')")
    @Log(title = "工序检测记录", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody RecLnspectionRecord recLnspectionRecord,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改工序检测记录",req,recLnspectionRecord);
        try {
            LoginUser loginUser = getLoginUser();
            recLnspectionRecord.setUpdateBy(loginUser.getUsername());
            recLnspectionRecord.setUpdateTime(new Date());
            recLnspectionRecordService.update(recLnspectionRecord);
            proWaringService.isWarning(recLnspectionRecord,null);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除工序检测记录
     */
    // @PreAuthorize("@ss.hasPermi('rec:recLnspectionRecord:remove')")
    @Log(title = "工序检测记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result<String> remove(@PathVariable Long[] ids,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除工序检测记录",req,null);
        try {
            return apiLog.fail("不能删除采集数据！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
